<?php

/**
 * Table/ContratHistoryTable.php
 */

namespace RHX\Model\Table;

use Zend\Db\Adapter\Adapter;
use Zend\Db\TableGateway\AbstractTableGateway;
use Zend\Db\ResultSet\ResultSet;
use RHX\Model\Object\ContratHistory;

class ContratHistoryTable extends AbstractTableGateway {

    protected $table = 'rh_contrat_history';

    /**
     * Constructeur
     *
     * @param \Zend\Db\Adapter\Adapter $adapter
     */
    public function __construct(Adapter $adapter) {
	$this->adapter			 = $adapter;
	$this->resultSetPrototype	 = new ResultSet();
	$this->resultSetPrototype->setArrayObjectPrototype(new ContratHistory($adapter));
	$this->initialize();
    }

    /**
     * Tous les historiques
     *
     * @return ResultSet
     */
    public function getAll() {
	return $this->select();
    }

    /**
     * Une Historique
     *
     * @param int $id
     * @return ContratHistory
     * @throws \Exception
     */
    public function get($id) {
	$row = $this->select(array('id' => $id))
		->current();
	if (!$row) {
	    throw new \Exception("L'historique des contrats #$id est introuvable");
	}

	return $row;
    }

    /**
     * Vérifier la présence d'une historique
     *
     * @param int $id
     * @return boolean
     */
    public function verify($id) {
	try {
	    $row = $this->get($id);

	    return true;
	}
	catch (\Exception $ex) {
	    return false;
	}
    }

    /**
     * Effacer une historique
     *
     * @param int $id
     * @return int
     */
    public function erase($id) {
	return $this->delete(array('id' => $id));
    }

    /**
     * Sauvegarder une historique
     *
     * @param \RHX\Model\Object\ContratHistory $history
     * @return int
     */
    public function save(ContratHistory $history) {
	$data	 = array(
	    'matricule'	 => (int) $history->matricule,
	    'contrat_id'	 => (int) $history->contrat_id,
	    'commentaire'	 => $history->commentaire,
	);
	$id	 = (int) $history->id;
	if ($id == 0) {
	    $this->insert($data);

	    return $id;
	}
	elseif ($this->verify($id)) {
	    $this->update($data, array('id' => $id));

	    return $id;
	}
    }

}

?>
